from flask import Flask, session, g
from exts import db, bootstrap, mail
from blueprints import qa_bp, user_bp
from flask_migrate import Migrate
from models import UserModel


app = Flask(__name__)
app.config.from_pyfile('config.py')

migrate = Migrate(app=app, db=db)
import command

def init_exts():
    db.init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)

def register_blueprint():
    app.register_blueprint(qa_bp)
    app.register_blueprint(user_bp)


init_exts()
register_blueprint()


@app.before_request
def brefore_request():
    user_id = session.get('user_id')
    if user_id:
        try:
            user = UserModel.query.get(user_id)
            # flask g绑定全局变量
            g.user = user
        except:
            g.user = None


# 请求到达:  before_request ---> view function ----> context_processor() ----> render_template()
@app.context_processor
def context_precessor():
    if hasattr(g, 'user'):
        return {'user': g.user}
    else:
        return {}
